﻿using System.Linq;
using System.Collections.Generic;

namespace SimbaRGVMonitor.Models
{
    class PathCollection : ModelCollection<string, Path>
    {
        protected override void UpdateCore(Dictionary<string, Path> currentItems, Dictionary<string, Path> newItems)
        {
            var addList = newItems.Keys.Except(currentItems.Keys).ToList();
            for(var i = addList.Count - 1; i >=0; i--)
            {
                var key = addList[i];
                var path = newItems[key];
                var endVertex = path.EndVertex;
                var startVertex = path.StartVertex;
                var reversePathNo = string.Format("{0}-{1}", endVertex, startVertex);
                if(currentItems.ContainsKey(reversePathNo))
                {
                    addList.RemoveAt(i);
                }
            }
            var updateList = newItems.Keys.Intersect(currentItems.Keys).ToList();
            var removeList = currentItems.Keys.Except(newItems.Keys).ToList();

            foreach (var key in addList)
            {
                var value = newItems[key];
                Add(key, value);
            }

            foreach (var key in updateList)
            {
                var value = newItems[key];
                Update(key, value);
            }

            foreach (var key in removeList)
            {
                var value = currentItems[key];
                Remove(key, value);
            }
        }
    }
}
